package com.biz.primus.ms.base.config;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

import java.util.concurrent.TimeUnit;

/**
 * @author yanweijin
 * @date 2017/6/10
 */
@Configuration
@Slf4j
public class JedisConfiguration {


	@Bean(destroyMethod = "destroy")
	ShardedJedisPool jedisPool(){
		RedisProperties p = redisProperties();
		log.info("redis configuration = {}",p);
		GenericObjectPoolConfig config = new GenericObjectPoolConfig();
		config.setMaxTotal(p.getMaxTotal());
		config.setMinIdle(p.getMinIdle());
		config.setTestWhileIdle(p.isTestWhileIdle());
		config.setTestOnBorrow(p.isTestOnBorrow());
		config.setMinEvictableIdleTimeMillis(p.getMinEvictableIdleTimeMillis());
		JedisShardInfo info = new JedisShardInfo(p.getHost(),p.getPort(),p.getTimeout());
		info.setPassword(Strings.emptyToNull(p.getPassword()));
		ShardedJedisPool pool = new ShardedJedisPool(config, Lists.newArrayList(info));
		try(ShardedJedis jedis = pool.getResource()){
			jedis.get("test-connection");
		}
		return pool;
	}

	@Bean
	@ConfigurationProperties("primus.redis")
	RedisProperties redisProperties(){
		return new RedisProperties();
	}

	@Getter
	@Setter
	@ToString
	private static class RedisProperties{
		private String host;
		private int port;
		private int timeout;
		private String password;
		private int minIdle = 3;
		private int maxTotal = 100;
		private boolean testWhileIdle = true;
		private boolean testOnBorrow = true;
		private long minEvictableIdleTimeMillis = TimeUnit.MINUTES.toMillis(10);
	}
}
